﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using FacialClub.Helpers;
using FacialClub.Models.Entities;
using FacialClub.Models.Interfaces;

namespace FacialClub.Models.Repositories
{
    /// <summary>
    /// ReferFriendRepository
    /// </summary>
    public class ReferFriendRepository : IReferFriendRepository
    {
        private readonly FacialClubEntities _db = new FacialClubEntities();
        private readonly IEmailTemplateRepository _emailTemplateRepository;

        /// <summary>
        /// ReferFriendRepository Constructor
        /// </summary>
        public ReferFriendRepository()
        {
            _emailTemplateRepository = new EmailTemplateRepository();
        }

        #region IReferFriendRepository Members

        /// <summary>
        /// Get All Refer Friend
        /// </summary>
        /// <returns></returns>
        public IQueryable<ReferFriend> GetAllReferFriend()
        {
            return _db.ReferFriends;
        }

        /// <summary>
        /// Get Refer Friend by Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ReferFriend GetReferFriend(int id)
        {
            return _db.ReferFriends.SingleOrDefault(d => d.ReferFriendId == id);
        }

        /// <summary>
        /// Get Refer Friend Details by Referee Name
        /// </summary>
        /// <param name="strQuery"></param>
        /// <returns></returns>
        public IQueryable<ReferFriend> GetReferFriendByName(string strQuery)
        {
            return _db.ReferFriends.Where(d => d.RefereeName.Contains(strQuery));
        }


        /// <summary>
        /// Get Refer Friend By Email
        /// </summary>
        /// <param name="strQuery"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<ReferFriend> GetReferFriendByEmail(string strQuery)
        {
            return _db.ReferFriends.Where(d => d.RefereeEmail.Contains(strQuery));
        }

        /// <summary>
        /// Get Refer Friend By Status
        /// </summary>
        /// <param name="strQuery"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<ReferFriend> GetReferFriendByStatus(bool strQuery)
        {
            return _db.ReferFriends.Where(r => r.IsTokenUsed.Equals(strQuery));
        }

        /// <summary>
        /// Update Token By Email
        /// </summary>
        /// <param name="strQuery"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void ReferFriendTokenUpdateByEmail(string strQuery)
        {
            //update implementation goes here...
        }


        /// <summary>
        /// Add Refer Friend in the Database
        /// </summary>
        /// <param name="referFriend"></param>
        public void Add(ReferFriend referFriend)
        {
            _db.ReferFriends.AddObject(referFriend);
        }

        /// <summary>
        /// Delete Template from Database
        /// </summary>
        /// <param name="referFriend"></param>
        public void Delete(ReferFriend referFriend)
        {
            _db.ReferFriends.DeleteObject(referFriend);
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="referFriend"></param>
        public void Update(ReferFriend referFriend)
        {
        }

        /// <summary>
        /// Save template in the database
        /// </summary>
        public void Save()
        {
            _db.SaveChanges();
        }

        /// <summary>
        /// Generate Token
        /// </summary>
        /// <param name="strLength"></param>
        public string GenerateToken(int strLength)
        {
            var rnd = new Random();
            var strRandom = "";
            for (var i = 0; i < strLength; i++)
            {
                var strNextNumber = rnd.Next(65, 90);
                //Get next number using random function between 65 to 90.
                var strNextRandom = new string((Char)strNextNumber, 1);
                //convert to ascii value to char          
                strRandom += strNextRandom;
            }
            return strRandom.ToLower();

        }
        /// <summary>
        /// Check whether the Customer is already subscribed or not
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool IsCustomerByEmail(string email)
        {
            return false;
        }

        /// <summary>
        /// Check whether the Subscriber is already subscribed or not
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool IsSubscriberByEmail(string email)
        {
            return false;
        }

        /// <summary>
        /// Get Referred Friend By Email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public List<String> GetReferredFriendByEmail(string email)
        {
            ReferFriend referFriend = GetReferFriendByEmail(email).SingleOrDefault();
            var friendList = new List<string>();
            friendList.AddRange(StringExtensions.SplitText(referFriend.FriendEmail, ","));
            return friendList;
        }

        /// <summary>
        /// Send Confirmation Email to Referee
        /// </summary>
        public void SendConfirmationEmail(string refereeName, string refereeEmail)
        {
            var emailTemplate = _emailTemplateRepository.FindEmailTemplateByName("ReferFriend_Confirmation").SingleOrDefault();
            var slReplace = new SortedList
                                {
                                    {"{referee_name}", refereeName},
                                    {"{referee_email}", refereeEmail},
                                    {"{base_url}", GeneralFunction.BaseSiteUrl}
                                };
            var strFromName = ConfigurationManager.AppSettings["FROMNAME"];
            var strFromEmail = ConfigurationManager.AppSettings["FROMEMAIL"];
            var strCCName = ConfigurationManager.AppSettings["CCNAME"];
            var strCCEmail = ConfigurationManager.AppSettings["CCEMAIL"];
            var strToName = refereeName;
            var strToEmail = refereeEmail;
            var strSubject = emailTemplate.EmailTemplateSubject;

            var strBody = StringExtensions.ReplaceStringFromList(emailTemplate.EmailTemplateDescription, slReplace);
            MailHelpers.SendMailMessageWithCredentials(strFromName, strFromEmail, strToName, strToEmail, strCCName,
                                                       strCCEmail, strSubject, strBody);
        }

        /// <summary>
        /// Send Invitation Email
        /// </summary>
        /// <param name="refereeName"></param>
        /// <param name="referredEmail"></param>
        public void SendInvitationEmail(string refereeName, string referredEmail)
        {
            var emailTemplate = _emailTemplateRepository.FindEmailTemplateByName("ReferedFriend_Invitation").SingleOrDefault();
            var referredFriend = GetReferredFriendByEmail(referredEmail);
            foreach (var key in referredFriend)
            {
                var slReplace = new SortedList
                                    {
                                        {"{referee_name}", refereeName},
                                        {"{referred_name}", key},
                                        {"{base_url}", GeneralFunction.BaseSiteUrl}
                                    };
                var strFromName = ConfigurationManager.AppSettings["FROMNAME"];
                var strFromEmail = ConfigurationManager.AppSettings["FROMEMAIL"];
                var strCCName = ConfigurationManager.AppSettings["CCNAME"];
                var strCCEmail = ConfigurationManager.AppSettings["CCEMAIL"];
                const string strToName = "";
                var strToEmail = referredEmail;
                var strSubject = emailTemplate.EmailTemplateSubject;

                var strBody = StringExtensions.ReplaceStringFromList(emailTemplate.EmailTemplateDescription,
                                                                        slReplace);
                MailHelpers.SendMailMessageWithCredentials(strFromName, strFromEmail, strToName, strToEmail, strCCName,
                                                           strCCEmail, strSubject, strBody);
            }
        }

        #endregion
    }
}